package org.chen.flight.service.flight;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.flight.OneWayFlightInfo;
import org.chen.common.flight.RoundTripFlightInfo;
import org.chen.common.flight.request.FlightSearchRequest;
import org.chen.common.translate.dto.BaiduTranslateRequestDTO;
import org.chen.flight.feign.BaiDuTranslateClient;
import org.chen.flight.service.FlightTranslationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OneWayFlightProcessService {

    @Autowired
    private FlightTranslationService translationService;

    /**
     * 处理单程航班数据
     */
    public List<OneWayFlightInfo> processFlights(List<OneWayFlightInfo> flights, FlightSearchRequest request) {
        if (flights == null || flights.isEmpty()) {
            return flights;
        }

        log.info("开始处理单程航班数据，原始数量: {}", flights.size());
        List<OneWayFlightInfo> validFlights;
        // 获取 orderTime 的值，假设 orderTime 是字符串类型，按格式解析
        if ("".equals(request.getOrderDate()) || request.getOrderDate() == null) {

            // 1. 基础有效性筛选
            validFlights = flights.stream()
                    .filter(this::isFlightValid)
                    .collect(Collectors.toList());
        } else {
            String orderTimeStr = request.getOrderDate();  // 获取请求中的 orderTime
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime orderTime = LocalDateTime.parse(orderTimeStr, formatter);  // 解析为 LocalDateTime

            // 1. 基础有效性筛选
            validFlights = flights.stream()
                    .filter(this::isFlightValid)
                    .filter(flight -> flight.getDepartureTime().isAfter(orderTime))  // 过滤掉 orderTime 之前的航班
                    .collect(Collectors.toList());
        }

        log.info("有效性筛选后数量: {}", validFlights.size());

        // 2. 智能去重 - 保留最低价格
        List<OneWayFlightInfo> deduplicatedFlights = deduplicateFlights(validFlights);

        // 3. 排序 - 直飞优先，然后按价格排序
        List<OneWayFlightInfo> sortedFlights;
        if (request.getDirectFlight()) {
            sortedFlights = deduplicatedFlights.stream()
                    .sorted(this::compareFlights)
                    .filter(OneWayFlightInfo::getIsDirectFlight)
                    .limit(new Random().nextInt(18, 24))
                    .collect(Collectors.toList());
            log.info("直飞航班处理完成，最终数量: {}", sortedFlights.size());
        } else {
            sortedFlights = deduplicatedFlights.stream()
                    .sorted(this::compareFlights)
                    .limit(new Random().nextInt(18, 24))
                    .collect(Collectors.toList());
            log.info("非直飞航班处理完成，最终数量: {}", sortedFlights.size());
        }

        log.info("处理完成，最终数量: {}", sortedFlights.size());
        return sortedFlights;

    }

    /**
     * 智能去重 - 针对相同航班组合保留最低价格
     */
    public List<OneWayFlightInfo> deduplicateFlights(List<OneWayFlightInfo> flights) {
        Map<String, OneWayFlightInfo> uniqueFlights = new LinkedHashMap<>();

        for (OneWayFlightInfo flight : flights) {
            String deduplicationKey = generateDeduplicationKey(flight);

            if (!uniqueFlights.containsKey(deduplicationKey)) {
                uniqueFlights.put(deduplicationKey, flight);
            } else {
                OneWayFlightInfo existingFlight = uniqueFlights.get(deduplicationKey);
                BigDecimal existingPrice = existingFlight.getAdultTotalPrice();
                BigDecimal currentPrice = flight.getAdultTotalPrice();

                if (currentPrice.compareTo(existingPrice) < 0) {
                    uniqueFlights.put(deduplicationKey, flight);
                }
            }
        }

        log.info("去重完成 - 原始: {}, 去重后: {}", flights.size(), uniqueFlights.size());
        return new ArrayList<>(uniqueFlights.values());
    }

    /**
     * 航班有效性检查
     */
    public boolean isFlightValid(OneWayFlightInfo flight) {
        // 检查价格有效性
        if (flight.getAdultTotalPrice() == null || flight.getAdultTotalPrice().compareTo(BigDecimal.ZERO) <= 0) {
            return false;
        }

        // 检查基础信息完整性
        if (flight.getFlightNumber() == null || flight.getFlightNumber().isEmpty()) {
            return false;
        }

        return flight.getDepartureTime() != null && flight.getArrivalTime() != null;
    }

    /**
     * 航班比较排序 - 直飞优先，然后按价格排序
     */
    public int compareFlights(OneWayFlightInfo a, OneWayFlightInfo b) {
        // 直飞优先
        boolean aIsDirect = Boolean.TRUE.equals(a.getIsDirectFlight());
        boolean bIsDirect = Boolean.TRUE.equals(b.getIsDirectFlight());

        if (aIsDirect && !bIsDirect) {
            return -1;
        } else if (!aIsDirect && bIsDirect) {
            return 1;
        }

        // 价格排序
        return a.getAdultTotalPrice().compareTo(b.getAdultTotalPrice());
    }

    /**
     * 生成去重键
     */
    private String generateDeduplicationKey(OneWayFlightInfo flight) {

        return flight.getFlightNumber() + "|" +
                formatTimeForKey(flight.getDepartureTime().toString()) + "|" +
                formatTimeForKey(flight.getArrivalTime().toString()) + "|" +
                flight.getDepartureAirportCode() + "-" +
                flight.getArrivalAirportCode() + "|" +
                flight.getCabinClass();
    }

    private String formatTimeForKey(String dateTimeStr) {
        if (dateTimeStr == null || dateTimeStr.length() < 13) {
            return dateTimeStr;
        }
        try {
            return dateTimeStr.substring(0, 13); // 精确到小时
        } catch (Exception e) {
            return dateTimeStr;
        }
    }

    /**
     * 处理已保存的航班数据（包含翻译）
     * 这个方法在数据保存到数据库后调用
     */
    public List<OneWayFlightInfo> processFlightsWithTranslation(List<OneWayFlightInfo> savedFlights, FlightSearchRequest request) {
        if (savedFlights == null || savedFlights.isEmpty()) {
            return savedFlights;
        }

        // 如果不需要翻译，直接返回
        if (!StringUtils.hasText(request.getLang()) || "zh".equals(request.getLang())) {
            return savedFlights;
        }

        try {
            log.info("开始并行翻译航班信息，数量: {}, 目标语言: {}", savedFlights.size(), request.getLang());
            long startTime = System.currentTimeMillis();

            // 收集所有需要翻译的文本
            List<String> allTexts = new ArrayList<>();
            List<Integer> textCounts = new ArrayList<>(); // 记录每个航班的文本数量

            for (OneWayFlightInfo flight : savedFlights) {
                List<String> flightTexts = translationService.prepareTextsForTranslation(flight);
                allTexts.addAll(flightTexts);
                textCounts.add(flightTexts.size());
            }

            // 多线程批量翻译
            List<String> translatedTexts = translationService.batchTranslateTexts(allTexts, "zh", request.getLang());

            // 应用翻译结果到航班对象
            List<OneWayFlightInfo> result = translateOnewayFlight(savedFlights, translatedTexts, textCounts);

            long endTime = System.currentTimeMillis();
            log.info("多线程翻译完成，耗时: {}ms", endTime - startTime);

            return result;

        } catch (Exception e) {
            log.error("多语言处理失败，使用原始数据", e);
            return savedFlights;
        }
    }

    /**
     * 翻译单个航班信息
     */
    private List<OneWayFlightInfo> translateOnewayFlight(List<OneWayFlightInfo> flights, List<String> translatedTexts, List<Integer> textCounts) {
        List<OneWayFlightInfo> result = new ArrayList<>();
        int textIndex = 0;

        for (int i = 0; i < flights.size(); i++) {
            OneWayFlightInfo flight = flights.get(i);
            int expectedTextCount = textCounts.get(i);

            // 检查翻译结果数量是否足够
            if (textIndex + expectedTextCount > translatedTexts.size()) {
                log.warn("翻译结果不足，航班 {} 使用原始数据", flight.getId());
                result.add(flight);
                continue;
            }

            try {

                flight.setFlightNumber(translatedTexts.get(0));
                flight.setAirline(translatedTexts.get(1));
                flight.setDuration(translatedTexts.get(2));
                flight.setDepartureAirport(translatedTexts.get(3));
                flight.setArrivalAirport(translatedTexts.get(4));
                flight.setDepartureCity(translatedTexts.get(5));
                flight.setArrivalCity(translatedTexts.get(6));
                flight.setBaggageInfo(translatedTexts.get(7));

                if (StringUtils.hasText(translatedTexts.get(8))) {
                    String[] split = translatedTexts.get(8).split("；");
                    List<String> purchaseNotes = Arrays.stream(split)
                            .map(String::trim)
                            .filter(StringUtils::hasText)
                            .collect(Collectors.toList());
                    flight.setPurchaseNotes(purchaseNotes);
                }

                result.add(flight);
                textIndex += expectedTextCount;

            } catch (Exception e) {
                log.error("应用翻译结果失败，航班: {}", flight.getId(), e);
                result.add(flight);
                textIndex += expectedTextCount;
            }
        }
        return result;
    }
}